package com.member.server.service.impl;

import com.member.server.domain.param.AccountCreateParam;
import com.member.server.domain.param.MemberSaveParam;
import com.member.server.entity.Account;
import com.member.server.entity.Member;
import com.member.server.mapper.AccountMapper;
import com.member.server.mapper.MemberMapper;
import com.member.server.service.IMemberBizService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author gaojx1993
 * @version 1.0
 * @description MemberBizServiceImpl
 * @since 2023/7/11 15:48
 */
@Service
public class MemberBizServiceImpl implements IMemberBizService {

    @Resource
    private MemberMapper memberMapper;

    @Resource
    private AccountMapper accountMapper;

    @Override
    public Long saveMember(MemberSaveParam memberSaveParam) {
        Member member = new Member();
        member.setDeleted(false);
        member.setGmtCreate(System.currentTimeMillis());
        member.setGmtUpdate(System.currentTimeMillis());
        member.setGmtRegister(System.currentTimeMillis());
        member.setName(memberSaveParam.getName());
        member.setValid(true);
        member.setStatus(1);
        member.setGender("M");

        memberMapper.insert(member);
        Long id = member.getId();
        if (id == null) {
            throw new RuntimeException("会员保存失败！");
        }
        return id;
    }

    @Override
    public Long createAccount(AccountCreateParam accountCreateParam) {
        Member member = memberMapper.selectById(accountCreateParam.getMemberId());
        if (member == null) {
            throw new RuntimeException("会员不存在！");
        }
        List<Account> accounts = accountMapper.selectByMemberId(member.getId());
        Integer type = accountCreateParam.getType() == null ? 1 : accountCreateParam.getType();
        if (accounts.stream().anyMatch(acc -> Objects.equals(acc.getType(), type))) {
            throw new RuntimeException("该类型钱包已存在！");
        }
        Long balance = accountCreateParam.getBalance();
        Account account = new Account();
        account.setMemberId(member.getId());
        account.setEnabled(true);
        account.setGmtCreate(System.currentTimeMillis());
        account.setGmtUpdate(System.currentTimeMillis());
        account.setType(type);
        account.setDeleted(false);
        account.setStatus(1);
        account.setBalance(balance == null || balance < 0 ? 0 : balance);
        accountMapper.insert(account);
        Long id = account.getId();
        if (id == null) {
            throw new RuntimeException("钱包创建失败！");
        }
        return id;
    }
}
